const config = require('./config');
var net = require('net');
var uuid = require('uuid');

var xml = require('./xml.js');

var currentIndex = 0;

var Stat = {
	'CONNET':0,
	'OPEN':1,
	
};

var clients = []; 
var VarList = [];

xml('./modbusRTU_Reg.xml',1,function(res){		 
	
	//console.log(res);
	//console.log(res.AI);
	VarList = res.AI;
    console.log(VarList);	
	/*
	for(var i in res.AI){
		
		console.log(res.AI[i].info);
		console.log(res.AI[i].TCP);
		console.log(res.AI[i].RTU);
		
	}
*/	
});




// tcp服务端


var server = net.createServer(function(socket){
    console.log('server: on connect');
	
	var client_uuid = uuid.v4();
    
    clients.push({
        "id": client_uuid,
        "ws": socket,
		"type":''
    });

    console.log(`client ${client_uuid} connected`);
	/**
     * 广播，发送到所有的客户端
     */
	function broadcastSend(type, message) {
    clients.forEach(function(v, i) {
        if(v.ws.readyState === Stat.OPEN) {
           
		   v.ws.send(message.toString());
        }
    })
}
    /**
     * 关闭服务，从客户端监听列表删除
     */
	 
    function closeSocket() {
        for(var i = 0; i < clients.length; i++) {
          if(clients[i].id == client_uuid) {
            //var disconnect_message = `${nickname} has disconnected`;
            //broadcastSend("notification", disconnect_message);
			console.log('disconnect_message.....');  
            clients.splice(i, 1);
          }
        }
    }

    socket.on('data', function(data){
        
	
	    try{
			var JsonObj = JSON.parse(data);
			console.log(typeof JsonObj);
			console.log(`client ${client_uuid} rev`);
			if(JsonObj.type != 'undefined' ){
			
				for(var i = 0; i < clients.length; i++) {
					if(clients[i].id == client_uuid) {
						clients[i].type = JsonObj.type ;		
						console.log(JsonObj.type);
						
						
					}
				}	
			}
		}catch(erro){
			
			console.log(erro);
		}
		
		console.log(`client ${client_uuid} rev`);
		console.log('server: on data {'+ data +'}');
		
		
		 for(var i = 0; i < clients.length; i++) {
          
		  console.log(clients[i].type);
        }
		
		

    });
	


    socket.on('close', function(){   
		  console.log(`client ${client_uuid} closed`);
		  closeSocket();
    });
});

setInterval(function(){
						
		for(var i = 0; i < clients.length; i++) {
			
			console.log('clients: '+clients[i].type);
			console.log('VarList: '+VarList[0].type);
			console.log('clients.ws.readyState : '+clients[i].ws.readyState );
			var type = VarList[0].type;
			
			if(clients[i].type == type) {
				
				var count = VarList.length;
				
				if(currentIndex % count === 0){currentIndex = 0};
				var buffer = new Buffer(VarList[currentIndex].RTU,'hex');
				
				if(clients[i].ws.readyState === 'open'){
					
					try{
						clients[i].ws.write(buffer);
						
					}catch(erro){
			
						console.log(erro);
					}
					
					currentIndex ++;
				}
				
				
				
			}
		}	

		
		
	
},150);





server.listen(config.modbus.port, config.modbus.IP, function(){
    console.log('server: on listen');
});


